import 'dart:io';

import 'package:desktop_drop/desktop_drop.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:file_selector/file_selector.dart';
import 'package:filelinker/alert.dart';
import 'package:filelinker/file_model.dart';
import 'package:filelinker/files.dart';
import 'package:filelinker/mdsn.dart';
import 'package:filelinker/netsev.dart';
import 'package:filelinker/recive.dart';
import 'package:filelinker/recv_text_page.dart';
import 'package:filelinker/send_text_popup.dart';
import 'package:filelinker/setting.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:gap/gap.dart';
import 'package:image_picker/image_picker.dart';
import 'package:nsd/nsd.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_manager/photo_manager.dart';

class PortalPage extends StatefulWidget {
  const PortalPage({super.key});

  @override
  State<PortalPage> createState() => _PortalPageState();
}

class _PortalPageState extends State<PortalPage> {
  final List<XFile> _files = [];
  bool _isShowingRecvPage = false;

  @override
  void initState() {
    MDNS.shared.onDeviceFound = () => setState(() {});
    NetService.shared.onGetFileNames = _onGetFileNames;
    NetService.shared.onGetText = _onGetText;
    _requestPermission();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    NetService.shared.context = context;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      floatingActionButton: IconButton(
        onPressed: _didTapSetting,
        icon: const Icon(Icons.settings),
        tooltip: "设置",
      ),
      appBar: _wAppBar(),
      body: _wBodyView(),
    );
  }

  AppBar? _wAppBar() {
    if (Platform.isAndroid || Platform.isIOS) {
      return AppBar(
        title: const Text('FileLinker'),
      );
    } else {
      return null;
    }
  }

  Widget _wBodyView() {
    return Column(
      children: [
        _wFileMainView(),
        _wSectionView(),
        _wDeviceListView(),
      ],
    );
  }

  Widget _wFileEmptyView() {
    if (Platform.isAndroid || Platform.isIOS) {
      return Center(
        child: IconButton(
          color: Theme.of(context).colorScheme.onPrimary,
          icon: const Icon(Icons.add),
          onPressed: _didTapAddButton,
          iconSize: 45,
        ),
      );
    }
    return InkWell(
      onTap: _didTapAddButton,
      child: Tooltip(
        message: "点击或拖拽文件到此处",
        child: Center(
          child: Text(
            "点击或拖拽文件到此处",
            style: TextStyle(
              color: Theme.of(context).colorScheme.onPrimary,
            ),
          ),
        ),
      ),
    );
  }

  Widget _wFileIconView(XFile file) {
    if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'].any((e) => file.name.endsWith(e))) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(3),
        child: Container(
          margin: const EdgeInsets.only(left: 1.5),
          child: Image.file(
            File(file.path),
            height: 30,
            width: 21,
            fit: BoxFit.cover,
          ),
        ),
      );
    }
    return Icon(
      Icons.description,
      color: Theme.of(context).colorScheme.onPrimary,
    );
  }

  Widget _wFileEditView() {
    return Column(
      children: [
        const Gap(15),
        Expanded(
          child: ListView.builder(
            itemBuilder: (_, idx) {
              final file = _files[idx];
              return Container(
                height: 35,
                margin: const EdgeInsets.symmetric(horizontal: 15),
                child: Row(
                  children: [
                    _wFileIconView(file),
                    const Gap(10),
                    Expanded(
                      child: Text(
                        file.name,
                        style: TextStyle(
                          color: Theme.of(context).colorScheme.onPrimary,
                        ),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ),
                    const Gap(10),
                    IconButton(
                      onPressed: () {
                        _files.removeAt(idx);
                        setState(() {});
                      },
                      icon: Icon(
                        Icons.close,
                        color: Theme.of(context).colorScheme.onPrimary,
                      ),
                    ),
                  ],
                ),
              );
            },
            itemCount: _files.length,
          ),
        ),
        Container(
          height: 40,
          margin: const EdgeInsets.symmetric(horizontal: 5),
          child: Row(
            children: [
              TextButton(
                onPressed: () => setState(() => _files.clear()),
                child: Text("取消",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.onPrimary,
                    )),
              ),
              const Spacer(),
              TextButton(
                onPressed: _didTapAddButton,
                child: Text("添加",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.onPrimary,
                    )),
              ),
              const Gap(10),
            ],
          ),
        ),
      ],
    );
  }

  Widget _wFileMainView() {
    if (MDNS.shared.isDesktop) {
      return DropTarget(
        onDragDone: (details) {
          for (var file in details.files) {
            debugPrint('file: ${file.name}');
            _files.add(file);
          }
          setState(() {});
        },
        child: _wFileListView(),
      );
    } else {
      return _wFileListView();
    }
  }

  Widget _wFileListView() {
    return Container(
      margin: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15.0),
        color: Theme.of(context).primaryColor,
      ),
      width: double.infinity,
      height: 160,
      child: _files.isEmpty ? _wFileEmptyView() : _wFileEditView(),
    );
  }

  Widget _wSectionView() {
    return Container(
      margin: const EdgeInsets.all(15),
      padding: const EdgeInsets.only(left: 5),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        border: Border(
            left: BorderSide(
          color: Theme.of(context).primaryColor,
          width: 5,
        )),
      ),
      child: const Text("附近设备"),
    );
  }

  Widget _wEmptyView() {
    return Expanded(
        child: Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            Icons.description,
            color: Theme.of(context).primaryColor,
            size: 80,
          ),
          const Gap(20),
          const Text(
            "没有发现设备",
          ),
          const Gap(50),
        ],
      ),
    ));
  }

  Widget _wDeviceListView() {
    List<Service> devices = MDNS.shared.devices;
    if (devices.isEmpty) {
      return _wEmptyView();
    }
    return Expanded(
        child: ListView.separated(
      itemBuilder: (context, index) {
        final service = devices[index];
        return Tooltip(
          message: "选择设备发送文件",
          child: ListTile(
            contentPadding: const EdgeInsets.only(left: 15),
            leading: const Icon(Icons.wifi_tethering),
            title: Text(service.xname(),
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                )),
            onTap: () => _didTapDevice(service),
            subtitle: Text("端口: ${service.port}",
                style: const TextStyle(
                  fontSize: 11,
                )),
            trailing: _wDeviceTrailingView(service),
          ),
        );
      },
      itemCount: devices.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          color: Theme.of(context).primaryColor.withAlpha((0.25 * 255).round()),
          height: 0.25,
        );
      },
    ));
  }

  Widget _wDeviceTrailingView(Service device) {
    return SizedBox.fromSize(
      size: const Size.fromWidth(100),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Spacer(),
          IconButton(
            onPressed: () => _didTapSendText(device),
            icon: const Icon(Icons.text_snippet),
            tooltip: "发送文本",
          ),
          IconButton(
            onPressed: () => _didTapDevice(device),
            icon: const Icon(Icons.chevron_right),
            tooltip: "选择设备发送文件",
          ),
        ],
      ),
    );
  }

  void _didTapDevice(Service device) {
    if (_files.isEmpty) {
      EasyLoading.showToast("没有选择文件");
      return;
    }
    Navigator.push(
      context,
      CupertinoPageRoute(
        builder: (context) => FilesSendPage(
          service: device,
          files: _files,
        ),
      ),
    );
  }

  void _didTapSetting() {
    Navigator.push(
      context,
      CupertinoPageRoute(
        builder: (context) => const SettingPage(),
      ),
    );
  }

  void _didTapAddButton() {
    if (Platform.isIOS) {
      _handleIOSAddFile();
    } else {
      _handleOtherAddFile();
    }
  }

  void _handleOtherAddFile() async {
    final xFile = await openFiles();
    for (var file in xFile) {
      debugPrint(file.name);
      _files.add(file);
    }
    setState(() {});
  }

  void _handleIOSAddFile() async {
    final picker = ImagePicker();
    EasyLoading.show(status: "Processing...");
    final flies = await picker.pickMultipleMedia();
    for (var file in flies) {
      debugPrint(file.name);
      _files.add(file);
    }
    EasyLoading.dismiss();
    setState(() {});
  }

  void _onGetFileNames() {
    if (_isShowingRecvPage) return;
    _isShowingRecvPage = true;
    Navigator.push(
        context,
        CupertinoPageRoute(
          builder: (context) => const RecivePage(),
        )).then(
      (_) {
        _isShowingRecvPage = false;
        NetService.shared.onGetFileNames = _onGetFileNames;
      },
    );
  }

  void _onGetText(String text) {
    Navigator.push(
      context,
      CupertinoPageRoute(
        builder: (context) => RecvTextPage(
          text: text,
        ),
      ),
    );
  }

  void _requestPermission() async {
    if (NetService.shared.permissionGranted) {
      return;
    }
    bool permission = false;
    if (Platform.isIOS) {
      permission = (await PhotoManager.requestPermissionExtend()).isAuth;
    } else if (Platform.isAndroid) {
      await Future.delayed(const Duration(milliseconds: 500));
      // ignore: use_build_context_synchronously
      final accepted = await Alert(context).showWarning("获取存储权限", "需要获取存储权限来保存文件，是否同意获取？");
      if (accepted) {
        final deviceINfoPlugin = DeviceInfoPlugin();
        final deviceInfo = await deviceINfoPlugin.androidInfo;
        final sdkInt = deviceInfo.version.sdkInt;
        debugPrint("sdkInt: $sdkInt");
        permission = await (sdkInt >= 33 ? Permission.manageExternalStorage : Permission.storage).request().isGranted;
        await NetService.shared.preload();
      }
    } else {
      permission = true;
    }
    NetService.shared.permissionGranted = permission;
    debugPrint("permissionGranted: ${NetService.shared.permissionGranted}");
  }

  void _didTapSendText(Service device) {
    showGeneralDialog(
      context: context,
      barrierDismissible: true,
      barrierLabel: "发送文本",
      pageBuilder: (context, animation, secondaryAnimation) => SendTextPopup(
        device: device,
      ),
    );
  }
}
